---
import type { CollectionEntry } from "astro:content";
import Layout from "@layouts/Layout.astro";
import Main from "@layouts/Main.astro";
import Header from "@components/Header.astro";
import Footer from "@components/Footer.astro";
import Pagination from "@components/Pagination.astro";
import Card from "@components/Card";
import { SITE, STATUS_LIST } from "@config";
import LinkButton from "@components/LinkButton.astro";
import StatusChart from "@components/StatusChart";
import getStatusCount from "@utils/getStatusCount";
import { getCollection } from "astro:content";

export interface Props {
  currentPage: number;
  totalPages: number;
  paginatedPosts: CollectionEntry<"posts">[];
  status: string | undefined;
  publishPage?: boolean;
}

const { currentPage, totalPages, paginatedPosts, publishPage } = Astro.props;
const status = Astro.props.status || "all";

function getStyle(tabStatus: string) {
  const base = "mr-4 select-none inline-block w-20 text-center px-4 py-2 ";
  return tabStatus === status
    ? base + " bg-skin-accent text-skin-inverted hover:text-skin-inverted"
    : base;
}

const countData = getStatusCount(await getCollection("posts"));
---

<Layout title={`${SITE.title}`}>
  <Header activeNav={publishPage ? "posts" : "tasks"} />
  <Main pageTitle="">
    {
      !publishPage && STATUS_LIST.find(x => x.status == status)?.hideInTab && (
        <StatusChart data={countData} client:only />
      )
    }
    {
      !publishPage && (
        <nav>
          {STATUS_LIST.map(
            ({ status, hideInTab, text, tabText }) =>
              !hideInTab && (
                <LinkButton
                  href={`/${status}/`}
                  className={getStyle(status)}
                  ariaLabel={status}
                >
                  {tabText || text}
                </LinkButton>
              )
          )}
        </nav>
      )
    }
    <ul>
      {
        paginatedPosts.map(({ id, data, slug, body }) => (
          <Card
            id={id}
            href={`/posts/${slug}/`}
            frontmatter={data}
            body={body}
            publishCard={publishPage}
          />
        ))
      }
    </ul>
  </Main>

  <Pagination
    {currentPage}
    {totalPages}
    prevUrl={`/${status}${currentPage - 1 !== 1 ? "/" + (currentPage - 1) : ""}/`}
    nextUrl={`/${status}/${currentPage + 1}/`}
  />

  <Footer noMarginTop={totalPages > 1} />
</Layout>
